<template>
  <div class="printConfig">
    <div class="print-type">
      <el-form ref="formRef" labelWidth="100px">
        <el-form-item label="打印内容" prop="printType">
          <el-radio-group v-model="printType">
            <el-radio :value="0">二维码+编码</el-radio>
            <el-radio :value="1">编码</el-radio>
            <el-radio :value="2">自定义模板</el-radio>
          </el-radio-group>
        </el-form-item>
        <template v-if="printType !== 2">
          <el-form-item label="二维码宽度">
            <el-input-number v-model="width" :precision="2" :min="0" />
          </el-form-item>
          <el-form-item label="二维码高度">
            <el-input-number v-model="height" :precision="2" :min="0" />
          </el-form-item>
        </template>
      </el-form>
    </div>

    <HiprintWeb
      v-if="printType === 2"
      :labelCodes="printLabels"
      :ids="printIds"
      :batchno="printBatchno"
      :type="printType"
      ref="hiprintWebRef"
    ></HiprintWeb>
    <HiprintRequest
      v-else
      ref="hiprintRequestRef"
      :labelCodes="printLabels"
      :ids="printIds"
      :batchno="printBatchno"
      :type="printType"
    ></HiprintRequest>

    <div class="dialog-footer">
      <el-button type="primary" v-if="isNewAdd" @click="onPrev">
        上一步
      </el-button>
      <el-button type="success" @click="submitForm"> 完成 </el-button>
      <el-button @click="onCancel">关闭</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, defineEmits, watch, onBeforeUnmount } from "vue";
import { useRouter } from "vue-router";
import { ElLoading, ElMessage } from "element-plus";
import store from "@/store/index.js";
import { useStore } from "vuex";
import api from "@/api/label.js";
import { downloadFn } from "@/api/index.js";
import HiprintWeb from "./hiprintWeb.vue";
import HiprintRequest from "./hiprintRequest.vue";

const router = useRouter();
const globalStore = useStore(); // 该方法用于返回store 实例
const emits = defineEmits(["prev"]);
const printType = ref(0);
const hiprintWebRef = ref();
const hiprintRequestRef = ref();
const width = ref(4);
const height = ref(6);
const props = defineProps({
  isNewAdd: { type: Number, default: 1 },
  labelCodes: { type: Array, default: () => [] },
  ids: { type: Array, default: () => [] },
  batchno: { type: [String, Number], default: "" },
});
const printLabels = ref([]);
const printIds = ref([]);
const printBatchno = ref("");

function onPrev() {
  emits("prev");
}

async function onExport() {
  const res = await downloadFn(api.exportByBatchno, {
    labelCodes: printLabels.value,
  });
  const blob = new Blob([res], {
    type: "text/plain;charset=utf-8",
  });
  const url = URL.createObjectURL(blob);
  const link = document.createElement("a");
  link.href = url;
  link.download = `printLog` + new Date().getTime();
  link.click();
  window.URL.revokeObjectURL(url);
  ElMessage.success(`导出成功！`);
  return true;
}

async function submitForm() {
  const loading = ElLoading.service({
    lock: true,
    text: "正在启动打印中...",
    background: "rgba(0, 0, 0, 0.7)",
  });
  const labels = store.getters.labels;
  if (labels?.length) {
    const res = await api.create({ labels });
    if (res.data) {
      printLabels.value = res.data;
      globalStore.commit("labels/addLabels", []);
    }
  }

  if (printLabels.value.length) {
    await onExport();
  }
  try {
    if (hiprintRequestRef.value) {
      await hiprintRequestRef.value.print({
        labelCodes: printLabels.value,
        ids: printIds.value,
        batchno: printBatchno.value,
        type: printType.value,
        width: width.value || 4,
        height: height.value || 6,
      });
    } else if (hiprintWebRef.value) {
      await hiprintWebRef.value.print({
        labelCodes: printLabels.value,
        ids: printIds.value,
        batchno: printBatchno.value,
        type: printType.value,
        width: width.value || 4,
        height: height.value || 6,
      });
    }
  } catch (error) {}
  loading.close();
}

function onCancel() {
  router.go(-1);
}

watch(
  () => props.labelCodes,
  () => {
    printLabels.value = props.labelCodes;
  },
  {
    immediate: true,
  }
);
watch(
  () => props.ids,
  () => {
    printIds.value = props.ids;
  },
  {
    immediate: true,
  }
);
watch(
  () => props.batchno,
  () => {
    printBatchno.value = props.batchno;
  },
  {
    immediate: true,
  }
);
onBeforeUnmount(() => {
  window.removeEventListener("afterprint", function () {}); // 在组件销毁前移除事件监听
});
</script>

<style lang="scss" scoped>
.print-type {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style>
